/*
 * 
 */
package co.edu.udistrital.erpgrid.utilidades.consola;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ResourceBundle;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import expectj.ExpectJ;
import expectj.ExpectJException;
import expectj.Spawn;
import expectj.TimeoutException;

// TODO: Auto-generated Javadoc
/**
 * La Clase ConsolaPrueba para ejecutar pruebas de los nodos.
 */
public class ConsolaPrueba {

	 /** El RS. */
 	private static transient ResourceBundle RS = ResourceBundle
	 .getBundle("utilidadesConf");

	/** La Constante LOG. */
	private static final Logger LOG = LoggerFactory.getLogger(ConsolaPrueba.class);

	/**
	 * Ejecutar archivos. Prueba para realizar las peticiones en la consola
	 *
	 * @param folder the folder
	 * @throws Exception the exception
	 */
	public static void ejecutarArchivos(String folder) throws Exception {
		String s;
		
		// Determinar en qué SO estamos
		String so = System.getProperty("os.name");
		// Comando para Linux
		if (!so.equals("Linux"))
			throw new Exception("No soportado");

		try {

			boolean okProxy = verificarProxy();
//			boolean okProxy = false;

			// Talk to it
			if (!okProxy){
				
				// Create a new ExpectJ object with a timeout of 5s
				ExpectJ expectinator = new ExpectJ();

				// Fork the process
				Spawn shell = expectinator.spawn("/bin/sh");
				
				shell.send("LD_LIBRARY_PATH=/opt/gt4/lib grid-proxy-init\n");
				shell.expectErr("Enter GRID pass phrase for this identity:");
				shell.send("globus\n");
				shell.expectErr("Done");
				shell.send("exit\n");
				shell.expectClose();
			}
			
			
			File carpetaArchivos = new File(folder);
			
			if(carpetaArchivos.isDirectory()){
				File listaOrdenes[] = carpetaArchivos.listFiles();
				for (File archivoComando : listaOrdenes) {
					StringBuilder resultado = new StringBuilder();
					//asegurarse que el archivo se pueda ejecutar
					archivoComando.setExecutable(true);
					
					// // Ejecutamos el comando
					Process p = Runtime.getRuntime().exec(archivoComando.getPath());

					 BufferedReader stdInput = new BufferedReader(new
					 InputStreamReader(p.getInputStream()));
					 //
					  BufferedReader stdError = new BufferedReader(new
					 InputStreamReader(p.getErrorStream()));
					 
					 //leermos los datos que se escriben en el error //globus los escribe ahi
					  while ((s = stdError.readLine()) != null) {
					  resultado.append(s);
					  LOG.info(s);
					  }
					  
				}
			}
			
			
			
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
	}

	/**
	 * Verificar proxy.
	 *
	 * @return verdadero, si es satisfactorio
	 */
	private static boolean verificarProxy(){
		
		boolean ok = false;
		// file.proxy /tmp/x509up_u1001
		//buscar archivo de proxy
		File file = new File(RS.getString("file.proxy"));
		if(file.exists()){
			ok = true;
		}
		return ok;
		
//		ExpectJ expectinator = new ExpectJ();
//		
//		
//
//		// Fork the process
//		Spawn shell = expectinator.spawn("/bin/sh");
//		
//		shell.send("LD_LIBRARY_PATH=/opt/gt4/lib grid-proxy-info\n");
//		String error = "Could not find a valid proxy certificate file location";
//		shell.send("exit\n");
//		shell.expectClose();
//		return shell.getCurrentStandardErrContents().indexOf(error) == -1;
	}

	/**
	 * Convert stream to string.
	 *
	 * @param is the is
	 * @return el string
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	static public String convertStreamToString(InputStream is)
			throws IOException {
		/*
		 * To convert the InputStream to String we use the Reader.read(char[]
		 * buffer) method. We iterate until the Reader return -1 which means
		 * there's no more data to read. We use the StringWriter class to
		 * produce the string.
		 */
		if (is != null) {
			Writer writer = new StringWriter();

			char[] buffer = new char[1024];
			try {
				Reader reader = new BufferedReader(new InputStreamReader(is));
				int n;
				while ((n = reader.read(buffer)) != -1) {
					writer.write(buffer, 0, n);
				}
			} finally {
				is.close();
			}
			return writer.toString();
		} else {
			return "";
		}
	}

}
